package permission_service

import (
	"errors"
	"starry_sky/internal/core"
	"starry_sky/internal/dal"
	"starry_sky/internal/model"
	"starry_sky/internal/tools/logger"
)

// CreatePermission 创建权限
func CreatePermission(permission *model.Permission) error {
	if permission.Type == core.Button {
		var hasButton int64
		err := dal.JudgmentRepetition[model.Permission](&hasButton, map[string]any{"Permission": permission.Permission}, permission.ID)
		if logger.HasError(err) {
			return errors.New("查询按钮权限是否重复失败")
		}
		if hasButton > 0 {
			return errors.New("按钮权限编码重复")
		}
	}
	permission.Status = true
	err := dal.Insert(permission)
	if logger.HasError(err) {
		return errors.New("创建权限失败")
	}
	return nil
}

// UpdatePermission 更新权限
func UpdatePermission(permission *model.Permission) error {
	var oldPermission model.Permission
	oldPermission.ID = permission.ID
	err := dal.FindById(&oldPermission)
	if logger.HasError(err) {
		return errors.New("查询权限失败")
	}
	permission.Status = oldPermission.Status
	if permission.Type == core.Button {
		var hasButton int64
		err := dal.JudgmentRepetition[model.Permission](&hasButton, map[string]any{"Permission": permission.Permission}, permission.ID)
		if logger.HasError(err) {
			return errors.New("查询按钮权限是否重复失败")
		}
		if hasButton > 0 {
			return errors.New("按钮权限编码重复")
		}
	}
	err = dal.Save(permission)
	if logger.HasError(err) {
		return errors.New("创建权限失败")
	}
	return nil
}

// DeletePermission 删除权限
func DeletePermission(permission *model.Permission) error {
	var count int64
	err := dal.CountByMap[model.Permission](&count, map[string]any{"parent_id": permission.ID})
	if logger.HasError(err) {
		return errors.New("查询子权限失败")
	}
	if count > 0 {
		return errors.New("存在子权限，无法删除")
	}
	err = dal.Delete(permission)
	if logger.HasError(err) {
		return errors.New("删除权限失败")
	}
	return nil
}
